import groovy.beans.Bindable
import net.sshiffon.*

class SshiffonModel {
	String MAIN_GROUP='Main'
	def config
	def configFoldername = System.getProperty('user.home') + '/.sshiffon/'
	def configFilename =  'sshiffonproperties.groovy'
	def configFile = new File(configFoldername + configFilename)
	@Bindable def savedConnections
	@Bindable boolean readyToConnect
	@Bindable boolean readyToSave
	@Bindable boolean empty=true
	@Bindable boolean  connectionSelected
	@Bindable def netInterfaces=[]
    @Bindable Map<String,?> activeConnectionTab = null
    List<?> openConnectionTabs = []
    ConnectionTabState state = new ConnectionTabState()

	/*
	@Bindable ConnectionSetting currentSetting= new ConnectionSetting()
	@Bindable ConnectionSetting settingFromPicker= new ConnectionSetting()

	public void copyToCurrent(ConnectionSetting setting)
	{
		setting.toMap().each{ k,v -> currentSetting."$k" = v }
	}
*/	
	
    public void loadConnections()
    {
        savedConnections = [ ((String)"${MAIN_GROUP}") : [] ] //preload main group ...

        //def group = []
        if(configFile.exists())
        {
            logger.debug(configFile.toURL())
            try {
                config = new ConfigSlurper().parse(configFile.toURL())
            } catch(Exception e)
            {
                logger.error ("error reading config. Clearing config ", e)
            }
        } else if(!new File(configFoldername).exists()) //make the folder
        {
            try {
                new File(configFoldername).mkdir();
            } catch (Exception e)
            {
                logger.error("Unexpected error - cant write config folder at ${configFoldername}", e)
            }
        }
        if(config==null || !config.containsKey('connections') || !config.containsKey('groups'))
        {
            logger.warn ("Config not valid. Resetting")
            //config = new groovy.util.ConfigObject()
            /*
            def defaultConfigScript = {
                def run() {
                    connections {
                        
                    }
                    groups {
                        Main = []
                    }
                }
            } as Script */
            config = new ConfigObject()
            config.groups = [ ((String)"${MAIN_GROUP}") :[]]
            config.connections= [:]
            //config = new ConfigSlurper().parse(defaultConfigScript)
        }
        def grouped=[];
        config.groups.each({group,members ->
                if(!savedConnections.containsKey(group))
                {
                	logger.trace("no group found called ${group}")
                    savedConnections.put(group,[]);
                }

                members.each ({ connName ->
                        savedConnections.get(group).add(connName)
                        grouped.add(connName)
                    })
            })
        
        config.connections.each({connName,connVars ->
                if(!grouped.contains(connName))
                {
                    savedConnections.get(((String)"${MAIN_GROUP}")).add(connName)
                }
                })
    }
    public void saveConnections()
    {
        if(!configFile.exists()) configFile.createNewFile()
        
            configFile.withWriter { writer ->
            config.writeTo(writer)
        }
    }
}

@Bindable class ConnectionTabState {
	@Bindable boolean dirty = false  
	@Bindable boolean connected = false
	@Bindable boolean sftpActive=false
	@Bindable boolean terminalActive=false
	@Bindable boolean configActive=false

	void updateActiveView(String viewName)
	{
		//view.edt {
			terminalActive=  'Terminal'.equals(viewName);
			configActive=  'Config'.equals(viewName);
			sftpActive=  'Sftp'.equals(viewName);
		//}
	}
}  